package com.freemalll.merchant.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.merchant.domain.dto.DTOInterfaceParams;
import com.freemalll.merchant.domain.entity.common.QxbLogEntity;
import com.freemalll.merchant.mapper.common.QxbLogMapper;
import com.freemalll.merchant.service.QxbService;
import com.freemalll.merchant.utils.CommonUtil;
import com.freemalll.merchant.utils.InterfaceOperational;
import com.freemalll.merchant.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 启信保  调用日志记录 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QxbServiceImpl extends ServiceImpl<QxbLogMapper, QxbLogEntity> implements QxbService {

    private final QxbLogMapper qxbLogMapper;
    private final InterfaceOperational interfaceOperational;

    @Override
    public String getBizQxbInfo(String licenseCode) {
        try {
            QxbLogEntity qxbLog = QxbLogEntity.builder()
                    .bizLicense(licenseCode)
                    .relationId(licenseCode)
                    .apiName("启信宝-工商照面")
                    .apiCode(DTOInterfaceParams.QX_businessFace)
                    .build();

            DTOInterfaceParams params = new DTOInterfaceParams();
            params.setType(DTOInterfaceParams.COMMON_TYPE);
            params.setRelationId(licenseCode);
            params.setSendType(DTOInterfaceParams.QX_businessFace);
            params.setInterfaceName("启信宝-工商照面");
            Map<String, Object> paramsMap = new HashMap<>(1);
            paramsMap.put("keyword", licenseCode);
            params.setUpt(JSON.toJSONString(paramsMap));
            String paramsStr = JSON.toJSONString(params);
            log.info("===>(启信宝)getBizQxbInfo 请求参数params：{}", paramsStr);
            qxbLog.setRequestTime(new Date());
            qxbLog.setRequestParams(paramsStr);
            Result result = interfaceOperational.send(params);
            String resultStr = JSON.toJSONString(result);
            log.info("===(启信宝)getBizQxbInfo 响应参数 result:{}", resultStr);
            qxbLog.setResponse(String.valueOf(result.getData()));
            qxbLog.setResponseTime(new Date());
            qxbLogMapper.insert(qxbLog);
            return String.valueOf(result.getData());
        } catch (Exception e) {
            log.info("===>(启信宝)getBizQxbInfo，保存qxbLog异常message：{}", e.getMessage());
        }
        return null;
    }


    @Override
    public String getQxbInfo(String merId, String licenseCode) {
        QxbLogEntity qxbLogEntity = qxbLogMapper.selectOne(Wrappers.<QxbLogEntity>lambdaQuery()
                .ge(QxbLogEntity::getRequestTime, LocalDate.now())
                .eq(QxbLogEntity::getApiCode, "QX_businessFace")
                .eq(QxbLogEntity::getBizLicense, licenseCode)
                .orderByDesc(QxbLogEntity::getRequestTime)
                .last(" limit 1 "));
        boolean has = false;
        if (Objects.nonNull(qxbLogEntity) && CommonUtil.isJson(qxbLogEntity.getResponse())) {
            JSONObject jsonObject = JSON.parseObject(qxbLogEntity.getResponse());
            if ("200".equals(jsonObject.getString("status"))) {
                has = true;
            }
        }
        if (has) {
            return qxbLogEntity.getResponse();
        } else {
            return this.getBizQxbInfo(licenseCode);
        }
    }

    @Override
    public String getQxbInfoByType(String merId, String licenseCode, String type) {
        /**
         * todo 模拟先从数据库中查
         */
        QxbLogEntity qxbLogEntity = qxbLogMapper.selectOne(Wrappers.<QxbLogEntity>lambdaQuery().eq(QxbLogEntity::getApiCode, type).eq(QxbLogEntity::getBizLicense, licenseCode).last(" limit 1 "));
        if (Objects.nonNull(qxbLogEntity) && CommonUtil.isJson(qxbLogEntity.getResponse())) {
            return qxbLogEntity.getResponse();
        }

        DTOInterfaceParams params = this.getInterfaceParams(type, licenseCode);
        try {
            QxbLogEntity qxbLog = QxbLogEntity.builder()
                    .bizLicense(licenseCode)
                    .relationId(licenseCode)
                    .apiName(params.getInterfaceName())
                    .apiCode(type)
                    .build();
            String paramsStr = params.getUpt();
            log.info("===>(启信宝)getBizQxbInfo 请求类型：{} 请求参数params：{}", type, paramsStr);
            qxbLog.setRequestTime(new Date());
            qxbLog.setRequestParams(paramsStr);
            Result result = interfaceOperational.send(params);
            String resultStr = JSON.toJSONString(result);
            log.info("===(启信宝)getBizQxbInfo 响应参数 result:{}", resultStr);
            qxbLog.setResponse(String.valueOf(result.getData()));
            qxbLog.setResponseTime(new Date());
            qxbLogMapper.insert(qxbLog);
            return String.valueOf(result.getData());
        } catch (Exception e) {
            log.info("===>(启信宝)getBizQxbInfo，保存qxbLog异常message：{}", e.getMessage());
        }
        return "";
    }


    /**
     * 请求参数
     *
     * @param interfaceType
     * @param licenseCode
     * @return
     */
    public DTOInterfaceParams getInterfaceParams(String interfaceType, String licenseCode) {
        DTOInterfaceParams params = new DTOInterfaceParams();
        params.setType(DTOInterfaceParams.COMMON_TYPE);
        params.setRelationId(licenseCode);
        params.setSendType(DTOInterfaceParams.QX_businessFace);
        Map<String, Object> map = new HashMap<>(2);
        switch (interfaceType) {
            case DTOInterfaceParams.QX_businessFace:
                params.setSendType(DTOInterfaceParams.QX_businessFace);
                params.setInterfaceName("启信宝-工商照面");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_simplifiedCancellation:
                params.setSendType(DTOInterfaceParams.QX_simplifiedCancellation);
                params.setInterfaceName("启信宝-简易注销");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_cancellation_record:
                params.setSendType(DTOInterfaceParams.QX_cancellation_record);
                params.setInterfaceName("启信宝-注销备案");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_illegal:
                params.setSendType(DTOInterfaceParams.QX_illegal);
                params.setInterfaceName("启信宝-严重违法");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_restrictingHighConsumption:
                params.setSendType(DTOInterfaceParams.QX_restrictingHighConsumption);
                params.setInterfaceName("启信宝-被限制高消费");
                map.put("ename", licenseCode);
                break;
            case DTOInterfaceParams.QX_dishonestExecutedEnterprise:
                params.setSendType(DTOInterfaceParams.QX_dishonestExecutedEnterprise);
                params.setInterfaceName("启信宝-失信被执行企业");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_executedEnterprise:
                params.setSendType(DTOInterfaceParams.QX_executedEnterprise);
                params.setInterfaceName("启信宝-被执行企业");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_equityFreeze:
                params.setSendType(DTOInterfaceParams.QX_equityFreeze);
                params.setInterfaceName("启信宝-股权冻结");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_filingInformation:
                params.setSendType(DTOInterfaceParams.QX_filingInformation);
                params.setInterfaceName("启信宝-立案信息");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_equityPledge:
                params.setSendType(DTOInterfaceParams.QX_equityPledge);
                params.setInterfaceName("启信宝-股权出质");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_changeRecord:
                params.setSendType(DTOInterfaceParams.QX_changeRecord);
                params.setInterfaceName("启信宝-变更记录");
                map.put("keyword", licenseCode);
                //变更类型（默认全部），1 企业名称变更 2 企业类型变更 3 证照号变更 4 注册资金变更 5 地址变更
                // 6 联系方式变更 7 经营范围变更 8 负责人变更 9 股东股权变更 10 人员变更 11 分支机构变更 12 隶属关系变更 13 期限变更 14 其他变更
                break;
            case DTOInterfaceParams.QX_administrativeSanction:
                params.setSendType(DTOInterfaceParams.QX_administrativeSanction);
                params.setInterfaceName("启信宝-行政处罚");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.Qx_commercialShareholders:
                params.setSendType(DTOInterfaceParams.Qx_commercialShareholders);
                params.setInterfaceName("启信宝-工商股东（工商公示）");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_abnormalOperation:
                params.setSendType(DTOInterfaceParams.QX_abnormalOperation);
                params.setInterfaceName("启信宝-经营异常");
                map.put("keyword", licenseCode);
                break;
            case DTOInterfaceParams.QX_courtNotice:
                params.setSendType(DTOInterfaceParams.QX_courtNotice);
                params.setInterfaceName("启信宝-法院公告");
                map.put("name", licenseCode);
                break;
            case DTOInterfaceParams.QX_announcementOfCourtSession:
                params.setSendType(DTOInterfaceParams.QX_announcementOfCourtSession);
                params.setInterfaceName("启信宝-开庭公告");
                map.put("name", licenseCode);
                break;
            default:
                throw BusinessException.businessValidateError("配置异常");
        }
        params.setUpt(JSON.toJSONString(map));
        return params;
    }

}
